package com.hermes.biz.dao.user.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.hermes.biz.common.model.user.UserDO;
import com.hermes.biz.dao.item.impl.ItemDAOImpl;
import com.hermes.biz.dao.user.UserDAO;

public class UserDAOImpl extends SqlMapClientDaoSupport implements UserDAO{

	private Logger log = Logger.getLogger(UserDAOImpl.class);
	
	@SuppressWarnings("unchecked")
	public List<UserDO> getList() {

		try {
			return getSqlMapClientTemplate().getSqlMapClient().queryForList("getAllUsers",null);
		} catch (SQLException e) {
			log.error(e);
		}
		return null;
	}

	public UserDO getUserByName(String userName) {

		try {
			return (UserDO)getSqlMapClientTemplate().getSqlMapClient().queryForObject("UserDAO.getUserByName",userName);
		} catch (SQLException e) {
			log.error(e);
		}
		return null;
	}

	public UserDO getUserById(long userId) {
		
		 try {
			return (UserDO)getSqlMapClientTemplate().getSqlMapClient().queryForObject("UserDAO.getUserById",userId);
		} catch (SQLException e) {
			log.error(e);
		}
		return null;
	}

	public boolean saveUser(UserDO user) {

		try {
			Object obj = this.getSqlMapClientTemplate().getSqlMapClient().insert("UserDAO.insertUser",user);
			long key = Long.parseLong(obj.toString());
			if(0==key){
				return true;
			}
		} catch (SQLException e) {
			log.error(e);
		}
		return false;
		
	}

	public void deleteUserByUserId(long userId) {

		try {
			this.getSqlMapClientTemplate().getSqlMapClient().delete("UserDAO.deleteUser", userId);
		} catch (SQLException e) {
			log.error(e);
		}
		
	}

	public void updateUser(UserDO user) {

		try {
			this.getSqlMapClientTemplate().getSqlMapClient().update("UserDAO.updateUser", user);
		} catch (SQLException e) {
			log.error(e);
		}
		
	}

	@SuppressWarnings("unchecked")
	public List<UserDO> getAllUserList() {
		try {
			return getSqlMapClientTemplate().getSqlMapClient().queryForList("getAllUsers",null);
		} catch (SQLException e) {
			log.error(e);
		}
		return null;
	}

	public int updateUserMin(UserDO user) {		
		try {
			return this.getSqlMapClientTemplate().getSqlMapClient().update("UserDAO.updateUserMin", user);
		} catch (SQLException e) {
			log.error(e);
		}
		return -1;
	}

	public void updateUserPassword(UserDO user) {
		try {
			this.getSqlMapClientTemplate().getSqlMapClient().update("UserDAO.updateUserPassword", user);
		} catch (SQLException e) {
			log.error(e);
		}
	}

	public boolean updateUserLogo(UserDO user) {
		try {
			int resultCnt = this.getSqlMapClientTemplate().getSqlMapClient().update("UserDAO.updateUserLogo", user);
			if(resultCnt>0){
				return true;
			}else{
				return false;
			}
		} catch (SQLException e) {
			log.error(e);
		}
		return false;
	}

}
